//
//  ImagePropertiesController.m
//  iOSStudy
//
//  Created by Evan Xie on 11/30/15.
//  Copyright © 2015 Family Wings. All rights reserved.
//

#import <AssetsLibrary/AssetsLibrary.h>

#import "ImagePropertiesController.h"
#import "ImageIOUtility.h"


@interface ImagePropertiesController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *photoView;
@property (weak, nonatomic) IBOutlet UITextView *propertyTextView;

@property (nonatomic, copy) NSURL *selectedPhotoURL;

@end

@implementation ImagePropertiesController

- (IBAction)presentPhotoPicker:(id)sender
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:NULL];
}

- (void)savePhoto:(NSData *)data
{
    [[NSFileManager defaultManager] removeItemAtPath:[self photoPath] error:nil];
    
    [data writeToFile:[self photoPath] atomically:YES];//you can save image later
}

- (NSString *)photoPath
{
    return [AMDirectoryDocuments stringByAppendingPathComponent:@"Photo"];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *photo = info[UIImagePickerControllerOriginalImage];
    self.photoView.image = photo;
    
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library assetForURL:info[UIImagePickerControllerReferenceURL] resultBlock:^(ALAsset *asset) {
        ALAssetRepresentation *rep = [asset defaultRepresentation];
        Byte *buffer = (Byte*)malloc((size_t)rep.size);
        NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:(NSUInteger)rep.size error:nil];
        NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];//this is NSData may be what you want
        [self savePhoto:data];
        
        self.selectedPhotoURL = [NSURL fileURLWithPath:[self photoPath]];
        
        NSDictionary *properties = [ImageIOUtility imagePropertiesDictionaryWithImageURL:self.selectedPhotoURL];
        self.propertyTextView.text = properties.description;
        
        [picker dismissViewControllerAnimated:YES completion:NULL];
        
    } failureBlock:^(NSError *error) {
        NSLog(@"Get Asset URL failed.");
    }];
}
@end
